<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <el-card class="welcome-card">
        <div class="welcome-content">
          <div class="welcome-text">
            <h2>欢迎回来，{{ userStore.userInfo?.name || '管理员' }}！</h2>
            <p>今天是 {{ currentDate }}，祝您工作愉快</p>
          </div>
          <div class="welcome-actions">
            <el-button type="primary" @click="handleQuickAction('create-exam')">
              <el-icon><Plus /></el-icon>
              创建试卷
            </el-button>
            <el-button @click="handleQuickAction('manage-questions')">
              <el-icon><Edit /></el-icon>
              题库管理
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon students">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.totalStudents }}</div>
                <div class="stats-label">学生总数</div>
                <div class="stats-trend positive">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ statsData.newStudents }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon questions">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.totalQuestions }}</div>
                <div class="stats-label">题目总数</div>
                <div class="stats-trend positive">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ statsData.newQuestions }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon exams">
                <el-icon><Notebook /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.totalExams }}</div>
                <div class="stats-label">试卷总数</div>
                <div class="stats-trend positive">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ statsData.newExams }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon submissions">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.totalSubmissions }}</div>
                <div class="stats-label">提交总数</div>
                <div class="stats-trend positive">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ statsData.newSubmissions }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>学生活跃度趋势</span>
                <el-select v-model="chartPeriod" size="small" style="width: 120px">
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                  <el-option label="最近90天" value="90d" />
                </el-select>
              </div>
            </template>
            <div ref="activityChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card">
            <template #header>
              <span>题目类型分布</span>
            </template>
            <div ref="questionTypeChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最新动态 -->
    <div class="activity-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="activity-card">
            <template #header>
              <div class="card-header">
                <span>最新考试</span>
                <el-link type="primary" @click="$router.push('/exams')">
                  查看全部
                </el-link>
              </div>
            </template>
            <div class="activity-list">
              <div
                v-for="exam in recentExams"
                :key="exam.id"
                class="activity-item"
              >
                <div class="activity-icon">
                  <el-icon><Notebook /></el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ exam.title }}</div>
                  <div class="activity-desc">{{ exam.description }}</div>
                  <div class="activity-time">{{ formatTime(exam.createdAt) }}</div>
                </div>
                <div class="activity-status">
                  <el-tag :type="getExamStatusType(exam.status)">{{ exam.status }}</el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="activity-card">
            <template #header>
              <div class="card-header">
                <span>系统通知</span>
                <el-link type="primary" @click="$router.push('/notifications')">
                  查看全部
                </el-link>
              </div>
            </template>
            <div class="activity-list">
              <div
                v-for="notification in recentNotifications"
                :key="notification.id"
                class="activity-item"
              >
                <div class="activity-icon">
                  <el-icon><Bell /></el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ notification.title }}</div>
                  <div class="activity-desc">{{ notification.content }}</div>
                  <div class="activity-time">{{ formatTime(notification.createdAt) }}</div>
                </div>
                <div class="activity-status">
                  <el-tag :type="getNotificationStatusType(notification.type)">{{ notification.type }}</el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Plus,
  Edit,
  User,
  Document,
  Notebook,
  DataAnalysis,
  ArrowUp,
  Bell
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

const router = useRouter()
const userStore = useUserStore()

// 图表引用
const activityChartRef = ref()
const questionTypeChartRef = ref()

// 图表周期
const chartPeriod = ref('7d')

// 当前日期
const currentDate = ref('')

// 统计数据
const statsData = reactive({
  totalStudents: 1248,
  newStudents: 23,
  totalQuestions: 3567,
  newQuestions: 45,
  totalExams: 189,
  newExams: 8,
  totalSubmissions: 5432,
  newSubmissions: 156
})

// 最新考试
const recentExams = ref([
  {
    id: 1,
    title: '数学期中考试',
    description: '高一数学期中测试',
    status: '进行中',
    createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000)
  },
  {
    id: 2,
    title: '英语听力测试',
    description: '英语听力专项练习',
    status: '已结束',
    createdAt: new Date(Date.now() - 5 * 60 * 60 * 1000)
  },
  {
    id: 3,
    title: '物理实验报告',
    description: '光学实验报告提交',
    status: '待开始',
    createdAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000)
  }
])

// 系统通知
const recentNotifications = ref([
  {
    id: 1,
    title: '系统维护通知',
    content: '系统将于今晚22:00-24:00进行维护',
    type: '系统',
    createdAt: new Date(Date.now() - 1 * 60 * 60 * 1000)
  },
  {
    id: 2,
    title: '新功能上线',
    content: '题目批量导入功能已上线',
    type: '功能',
    createdAt: new Date(Date.now() - 3 * 60 * 60 * 1000)
  },
  {
    id: 3,
    title: '数据备份完成',
    content: '每日数据备份已完成',
    type: '备份',
    createdAt: new Date(Date.now() - 6 * 60 * 60 * 1000)
  }
])

// 处理快速操作
const handleQuickAction = (action) => {
  switch (action) {
    case 'create-exam':
      router.push('/exams/create')
      break
    case 'manage-questions':
      router.push('/questions')
      break
    default:
      ElMessage.info('功能开发中...')
  }
}

// 格式化时间
const formatTime = (date) => {
  return formatDistanceToNow(date, {
    addSuffix: true,
    locale: zhCN
  })
}

// 获取考试状态类型
const getExamStatusType = (status) => {
  const statusMap = {
    '进行中': 'success',
    '已结束': 'info',
    '待开始': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取通知状态类型
const getNotificationStatusType = (type) => {
  const typeMap = {
    '系统': 'warning',
    '功能': 'success',
    '备份': 'info'
  }
  return typeMap[type] || 'info'
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 这里可以集成 ECharts 或其他图表库
  // 示例代码，实际使用时需要引入相应的图表库
  console.log('初始化图表...')
}

// 获取统计数据
const fetchStatsData = async () => {
  try {
    // 这里调用实际的API获取统计数据
    console.log('获取统计数据...')
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取最新数据
const fetchRecentData = async () => {
  try {
    // 这里调用实际的API获取最新数据
    console.log('获取最新数据...')
  } catch (error) {
    console.error('获取最新数据失败:', error)
  }
}

// 组件挂载
onMounted(async () => {
  // 设置当前日期
  currentDate.value = new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
  
  // 获取数据
  await Promise.all([
    fetchStatsData(),
    fetchRecentData(),
    initCharts()
  ])
})
</script>

<style lang="scss" scoped>
.dashboard {
  padding: var(--spacing-6);
  
  @media (max-width: 768px) {
    padding: var(--spacing-4);
  }
}

.welcome-section {
  margin-bottom: var(--spacing-6);
}

.welcome-card {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
  color: white;
  border: none;
  
  :deep(.el-card__body) {
    padding: var(--spacing-8);
  }
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: var(--spacing-6);
    text-align: center;
  }
}

.welcome-text {
  h2 {
    font-size: var(--font-size-3xl);
    font-weight: 600;
    margin-bottom: var(--spacing-2);
  }
  
  p {
    font-size: var(--font-size-lg);
    opacity: 0.9;
  }
}

.welcome-actions {
  display: flex;
  gap: var(--spacing-4);
  
  @media (max-width: 768px) {
    flex-direction: column;
    width: 100%;
  }
  
  .el-button {
    &.el-button--primary {
      background: rgba(255, 255, 255, 0.2);
      border-color: rgba(255, 255, 255, 0.3);
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }
    
    &:not(.el-button--primary) {
      background: transparent;
      border-color: rgba(255, 255, 255, 0.5);
      color: white;
      
      &:hover {
        background: rgba(255, 255, 255, 0.1);
        border-color: rgba(255, 255, 255, 0.7);
      }
    }
  }
}

.stats-section {
  margin-bottom: var(--spacing-6);
}

.stats-card {
  height: 120px;
  
  :deep(.el-card__body) {
    padding: var(--spacing-6);
    height: 100%;
  }
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
  gap: var(--spacing-4);
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: var(--border-radius-xl);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--font-size-2xl);
  color: white;
  
  &.students {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  &.questions {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }
  
  &.exams {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }
  
  &.submissions {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: var(--font-size-3xl);
  font-weight: 700;
  color: var(--gray-800);
  line-height: 1;
  margin-bottom: var(--spacing-1);
}

.stats-label {
  font-size: var(--font-size-sm);
  color: var(--gray-600);
  margin-bottom: var(--spacing-1);
}

.stats-trend {
  display: flex;
  align-items: center;
  gap: var(--spacing-1);
  font-size: var(--font-size-xs);
  
  &.positive {
    color: var(--success-color);
  }
  
  &.negative {
    color: var(--error-color);
  }
}

.charts-section {
  margin-bottom: var(--spacing-6);
}

.chart-card {
  height: 400px;
  
  :deep(.el-card__body) {
    padding: 0;
    height: calc(100% - 60px);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.chart-container {
  width: 100%;
  height: 100%;
  padding: var(--spacing-4);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--gray-500);
  background: var(--gray-50);
  border-radius: var(--border-radius);
}

.activity-section {
  .activity-card {
    height: 400px;
    
    :deep(.el-card__body) {
      padding: 0;
      height: calc(100% - 60px);
      overflow-y: auto;
    }
  }
}

.activity-list {
  padding: var(--spacing-4);
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-4);
  padding: var(--spacing-4);
  border-radius: var(--border-radius);
  transition: background-color var(--transition-fast);
  
  &:hover {
    background-color: var(--gray-50);
  }
  
  &:not(:last-child) {
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: var(--border-radius-lg);
  background: var(--primary-color);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
  min-width: 0;
}

.activity-title {
  font-weight: 600;
  color: var(--gray-800);
  margin-bottom: var(--spacing-1);
  @include text-ellipsis;
}

.activity-desc {
  font-size: var(--font-size-sm);
  color: var(--gray-600);
  margin-bottom: var(--spacing-1);
  @include text-ellipsis;
}

.activity-time {
  font-size: var(--font-size-xs);
  color: var(--gray-500);
}

.activity-status {
  flex-shrink: 0;
}
</style>